﻿using System;
using System.Collections.Generic;
using System.Xml;
using ARD.Common;
using ARD.Configuration;
using ARD.Logging;
using ARD.ServiceManagement;
using ARD.EventRouting;
using SharpObjects.SearchEngine.Common.ApplicationEvents;
using System.IO;

namespace SharpObjects.SearchEngine.Common.Services
{
    public class LoggingService : ILoggingService, IConfigurationObject, IService
    {
        EventBus eventBus = null;

        public LoggingService()
        {
        }

        protected void LoggingEventHandler(IApplicationEvent ev)
        {
            try
            {
                if (ev is LoggingApplicationEvent)
                {
                    LoggingApplicationEvent logEv = (LoggingApplicationEvent)ev;

                    ILogCategory category = Log.GetCategory(logEv.Message.LogCategory);
                    category.WriteMessage(logEv.Message.Message, new Location(logEv.Message.LogMessageOrigin));
                }
            }
            catch (Exception)
            {
                // can't do anything
            }
        }

        #region ILoggingService Members

        public ILogProxy Proxy
        {
            get
            {
                return Log.proxy;
            }
        }

        #endregion


        #region IConfigurationObject Members

        public string Id { get; set; }

        public void Initialize(System.Xml.XmlElement initialization_section)
        {
            XmlConfig init = new XmlConfig(initialization_section);
            this.Id = init.GetString("@id", this.Id);

            XmlElement loggingElem = (XmlElement)init.GetNode("/configuration/logging");
            Log.Configure(loggingElem);

            this.eventBus = ServiceManager.Instance.GetService<EventBus>("default_event_bus");
            this.eventBus.Subscribe(typeof(LoggingApplicationEvent), new EventBus.EventHandler(LoggingEventHandler));

            string[] logDirectories = init.GetStrings("//logging/targets/target/configuration_section/log_directory");

            foreach (string logDirectory in logDirectories)
            {
                DirectoryInfo di = new DirectoryInfo(logDirectory);

                if(!di.Exists)
                {
                    di.Create();
                }
            }
        }

        #endregion

        #region IService Members

        public string ServiceId
        {
            get { return this.Id; }
        }

        public ServiceManager ServiceManager { get; set; }

        public Type ServiceType
        {
            get { return typeof(ILoggingService); }
        }

        #endregion

    }
}
